//
//  SDAnswerTestAllResultVC.m
//  skinDetection
//
//  Created by  liangzhun on 2019/3/6.
//  Copyright © 2019年  liangzhun. All rights reserved.
//

#import "SDAnswerTestAllResultVC.h"
#import "SDAnswerDetectionHeaderView.h"
#import "SDSkinKindSelectView.h"
#import "SDAnswerTestHeaderView.h"


#import "SDProductDetailVC.h"
#import "SDAnswerTestResultCell.h"
#import "SDAnswerTestResultProductCell.h"
#import "SDAnswerTestResultProductCell2.h"
#import "SDProductListCell.h"

#import "SDAnswerTestData.h"
#import "SDAnswerTestChildList.h"
#import "SDAnswersDetectionModel.h"
#import "SDQuestionnaireViewController.h"

#import "SDAnswerTestResultData.h"
#import "SDAnswerTestResultProductList.h"

static NSString *const cellIden = @"SDAnswerTestResultProductCell";
static NSString *const cellIden1 = @"SDAnswerTestResultCell";
static NSString *const cellIden2 = @"SDAnswerTestResultProductCell2";
static NSString *const headerIden = @"SDAnswerTestHeaderView";
static NSString *const cellIden3 = @"SDProductListCell";


@interface SDAnswerTestAllResultVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (weak, nonatomic) IBOutlet UIView *headerView;

@property (weak, nonatomic) IBOutlet UIView *layerView;

@property (weak, nonatomic) IBOutlet UIView *LabView;

@property (weak, nonatomic) IBOutlet UILabel *topLab;

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bgImageHeight;

@property (nonatomic ,strong) SDAnswerDetectionHeaderView *scrHeaderView;

@property (nonatomic ,strong) SDSkinKindSelectView *bottomView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightLayerView;

@property (nonatomic ,strong) CAGradientLayer *bgLayer;

@end

@implementation SDAnswerTestAllResultVC

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.navHeight.constant = SDNavBar_Height;
    [self layOut];
    [self setViews];
    [self showView];
    [self loadData];
    [self.view bringSubviewToFront:self.bottomView];
}
- (void)loadData
{
    [[SDAnswersDetectionModel shareInstance] loadDataWithBlock:^(BOOL success) {
        
        [self.scrHeaderView.collectionView reloadData];
         [SDAnswersDetectionModel shareInstance].answerTestType = (int)self.scrHeaderView.indexpath.row + 1;
        [self showView];
        
    }];
    
}
- (void)setViews
{
     self.LabView.layer.shadowColor = rgba(0, 0, 0, 0.07).CGColor;
     [self.collectionView registerNib:[UINib nibWithNibName:cellIden bundle:nil] forCellWithReuseIdentifier:cellIden];
     [self.collectionView registerNib:[UINib nibWithNibName:cellIden2 bundle:nil] forCellWithReuseIdentifier:cellIden2];
     [self.collectionView registerNib:[UINib nibWithNibName:cellIden1 bundle:nil] forCellWithReuseIdentifier:cellIden1];
    [self.collectionView registerNib:[UINib nibWithNibName:cellIden3 bundle:nil] forCellWithReuseIdentifier:cellIden3];
    
    [self.collectionView registerNib:[UINib nibWithNibName:headerIden bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIden];
    
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
   
    SDAnswerTestResultData *data = [SDAnswersDetectionModel shareInstance].resultDic[[NSString stringWithFormat:@"%lu",(unsigned long)[SDAnswersDetectionModel shareInstance].answerTestType]];
    if (section == 0) {
        return data.feature.length > 0? 1:0;
    }
    return data.productList.count;
    
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        SDAnswerTestResultCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIden1 forIndexPath:indexPath];
        
        SDAnswerTestResultData *data = [SDAnswersDetectionModel shareInstance].resultDic[[NSString stringWithFormat:@"%lu",(unsigned long)[SDAnswersDetectionModel shareInstance].answerTestType]];
        [cell.contentLab setAttributedText:nil];
        if (data.feature.length > 0)
        {
            
            NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
            style.lineSpacing = 5.0f;
            NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:data.feature attributes:@{NSParagraphStyleAttributeName:style}];
            [cell.contentLab setAttributedText:att];
            
        }
        
        return cell;
        
    }else{
     
        SDProductListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIden3 forIndexPath:indexPath];
         SDAnswerTestResultData *data = [SDAnswersDetectionModel shareInstance].resultDic[[NSString stringWithFormat:@"%lu",(unsigned long)[SDAnswersDetectionModel shareInstance].answerTestType]];
        SDAnswerTestResultProductList *list = data.productList[indexPath.row];
        [cell.productImage sd_setImageWithURL:[NSURL URLWithString:list.sImg]];
        [cell.productTitle setText:list.productName];
        return cell;
        
    }
    
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    SDAnswerTestHeaderView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIden forIndexPath:indexPath];
   
    header.titleLab.text = indexPath.section == 0? @"特征":@"推荐产品";
    SDAnswerTestResultData *data = [SDAnswersDetectionModel shareInstance].resultDic[[NSString stringWithFormat:@"%lu",(unsigned long)[SDAnswersDetectionModel shareInstance].answerTestType]];
    if (indexPath.section == 0) {

        header.hidden = data.feature.length > 0? NO:YES;

    }else{
       header.hidden = data.productList.count > 0? NO:YES;
    }
    return header;
    
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{

    if (indexPath.section == 0) {
        
        SDAnswerTestResultData *data = [SDAnswersDetectionModel shareInstance].resultDic[[NSString stringWithFormat:@"%lu",(unsigned long)[SDAnswersDetectionModel shareInstance].answerTestType]];
       
        CGFloat height = 0 ;
        if (data.feature.length > 0)
        {
            
            NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
            style.lineSpacing = 5.f;
            NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:data.feature attributes:@{NSParagraphStyleAttributeName:style}];
            
            height = [SDMethodTool getAttTextHeightWithText:att withTextFontSize:Font(15) Width:SDMainScreenWidth - 30] + 2;
        }
        
        return CGSizeMake(SDMainScreenWidth, height + 40);
        
    }
    
    return CGSizeMake((SDMainScreenWidth - 45)/2.0, 78 + (SDMainScreenWidth - 45 - 60)/2.0);
    
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 15, 0, 15);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 15;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 15;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    CGFloat height = 0;
    SDAnswerTestResultData *data = [SDAnswersDetectionModel shareInstance].resultDic[[NSString stringWithFormat:@"%lu",(unsigned long)[SDAnswersDetectionModel shareInstance].answerTestType]];

    if (section == 0) {

        height = data.feature.length > 0? 127:69;

    }else{
        height = data.productList.count > 0? 58:0;
    }
    return CGSizeMake(SDMainScreenWidth, height);
    
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)return;
    SDAnswerTestResultData *data = [SDAnswersDetectionModel shareInstance].resultDic[[NSString stringWithFormat:@"%lu",(unsigned long)[SDAnswersDetectionModel shareInstance].answerTestType]];
    SDAnswerTestResultProductList *list = data.productList[indexPath.row];
     if (list.bImg.length == 0)return;
    SDProductDetailVC *vc = [SDMethodTool getViewControlWithIdentifier:NSStringFromClass([SDProductDetailVC class])];
    vc.list = list.bImg;
    [self.navigationController pushViewController:vc animated:YES];
    
}
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    SDAnswerTestResultData *data = [SDAnswersDetectionModel shareInstance].resultDic[[NSString stringWithFormat:@"%lu",(unsigned long)[SDAnswersDetectionModel shareInstance].answerTestType]];
//
//    if (data.feature.length == 0)return;
//
//    UIColor *colorCollection = scrollView.contentOffset.y < 127? SDClearColor:rgba(245, 245, 245, 1);
//    UIColor *colorView = scrollView.contentOffset.y < 127? rgba(245, 245, 245, 1):SDWhiteColor;
//    if (colorCollection != self.collectionView.backgroundColor)[self.collectionView setBackgroundColor:colorCollection];
//    if (colorView != self.view.backgroundColor)[self.view setBackgroundColor:colorView];
//
//}
- (void)layOut
{
    [self.scrHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.left.top.bottom.equalTo(self.headerView);
    }];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.layerView.mas_bottom);
        make.right.left.bottom.equalTo(self.view);
    }];
    
}
- (SDAnswerDetectionHeaderView *)scrHeaderView
{
    if (!_scrHeaderView) {
        
        _scrHeaderView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([SDAnswerDetectionHeaderView class]) owner:nil options:nil].lastObject;
        [_scrHeaderView setViews];
        
        @weakify(self);
        _scrHeaderView.block = ^(NSIndexPath *IndexPath) {
            @strongify(self);
            [SDAnswersDetectionModel shareInstance].answerTestType = (int)IndexPath.row + 1;
            
            [self showView];
        };
        
        [self.headerView addSubview:_scrHeaderView];
        
    }
    
    return _scrHeaderView;
    
}
-(SDSkinKindSelectView *)bottomView
{
    if (!_bottomView) {
        
        _bottomView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([SDSkinKindSelectView class]) owner:nil options:nil].lastObject;
        _bottomView.hidden = YES;
        [self.view addSubview:_bottomView];
        
    }
    return _bottomView;
    
}

- (void)reloadBottomView
{
   
     SDAnswerTestData *data = [SDAnswersDetectionModel shareInstance].dataArray[[SDAnswersDetectionModel shareInstance].answerTestType - 1];
    
    CGFloat width = 0.0;
    CGFloat lastWidth = 0.0;
    CGFloat left = 0.0;
    int height = 0;
   
    if (data.desc.length > 0) {
        
       
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        [style setLineSpacing:5];
        [style setAlignment:NSTextAlignmentLeft];
        NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:data.desc];
        [att addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, att.length)];
        
        if ([data.desc containsString:@"（"]&&[data.desc containsString:@"）"]) {
            
            NSRange startRang = [data.desc rangeOfString:@"（"];
            NSRange endRang = [data.desc rangeOfString:@"）"];
            NSRange rang = NSMakeRange(startRang.location, endRang.location - startRang.location + 1);
            [att addAttribute:NSFontAttributeName value:Font(17) range:rang];
            [att addAttribute:NSForegroundColorAttributeName value:rgba(163, 161, 162, 1) range:rang];
            
        }
        
        [self.bottomView.titleLab setAttributedText:att];
        
    }
   
    for (UIView *view in self.bottomView.subviews) {
        if (view != self.bottomView.titleLab)[view removeFromSuperview];
    }
    
    for (int s = 0 ; s < data.childList.count; s++) {
      
        SDAnswerTestChildList *list = data.childList[s];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = s + 1;
        [button.titleLabel  setFont:Font(15)];
        [button.layer setBorderWidth:1];
        [button.layer setCornerRadius:17.5];
        [button.layer setMasksToBounds:YES];
        [button.layer setBorderColor:rgba(255, 120, 155, 1).CGColor];
        [button setTitleColor:rgba(77, 72, 74, 1) forState:UIControlStateNormal];
        [button setTitle:list.desc forState:UIControlStateNormal];
        [button handleControlEvent:UIControlEventTouchUpInside withBlock:^{
            
            if (data.subjectList.count == 0) {
                
                [self getResultWithAnswer:[self getAnswerWithTag:(int)button.tag]];
                
            }else{
                
                button.tag != data.childList.count? [self getResultWithAnswer:[self getAnswerWithTag:(int)button.tag]]:[self goQuestionnaireVC];
                
            }
            
        }];
        [self.bottomView addSubview:button];
        
        
        CGFloat strW = [SDMethodTool getTextWidthWithText:list.desc Height:15 Font:Font(15)] + 40;
        width = width + strW + 15;
        
        if (s > 0&&s<= data.childList.count - 1&&width <= SDMainScreenWidth - 15) {
            SDAnswerTestChildList *list2 = data.childList[s - 1];
            lastWidth = [SDMethodTool getTextWidthWithText:list2.desc Height:15 Font:Font(15)] + 40;
        }
        
        if (width > SDMainScreenWidth - 15) {
            
            width = 0.0;
            width = width + strW + 15;
            left = 15.0;
            height = height + 1;
            
        }else{
            
         left = left + 15 + lastWidth;
            
        }
        
        if (strW > SDMainScreenWidth - 30) {
            strW = SDMainScreenWidth - 30;
            [button.titleLabel setAdjustsFontSizeToFitWidth:YES];
        }
        
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(35);
            make.left.mas_equalTo(left);
            make.width.mas_equalTo(strW);
            make.top.equalTo(self.bottomView.titleLab.mas_bottom).offset( 30 + (35 + 15)*height);
        }];
        
    }

    
}
- (void)showView
{
    
  SDAnswerTestResultData *dataResult = [SDAnswersDetectionModel shareInstance].resultDic[[NSString stringWithFormat:@"%d",[SDAnswersDetectionModel shareInstance].answerTestType]];
  if (dataResult.desc.length > 0)[self getTopTitleWithStr:dataResult.desc];
  BOOL hasResult = dataResult? YES:NO;
  self.collectionView.hidden = !hasResult;
  self.LabView.hidden = !hasResult;
  self.bottomView.hidden = hasResult;
  self.heightLayerView.constant = hasResult? 170 - 20 + SDStatusBarHeight:130 - 20 + SDStatusBarHeight;
  self.bgImageHeight.constant = hasResult? 170 - 20 + SDStatusBarHeight:130 - 20 + SDStatusBarHeight;
  if (!hasResult)[self reloadBottomView];
  [self.collectionView reloadData];
    

}
/**
 进入问卷调查页面
 */
- (void)goQuestionnaireVC
{
    SDQuestionnaireViewController *vc = [SDMethodTool getViewControlWithIdentifier:NSStringFromClass([SDQuestionnaireViewController class])];
    vc.block = ^(NSDictionary * _Nonnull dic) {
        [self showResultWithDic:dic];
        if ([self isCreateTestReport])[self createTestReport];
    };
    
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (void)createTestReport
{
    NSDictionary *dic = @{@"result":[self getAllAnswers]};
    [SDNetwork postQuestionGenerateReportWithParame:dic Finish:^(NSDictionary * _Nullable dic, NSError * _Nullable error) {
       
    }];
}
- (BOOL)isCreateTestReport
{
    
    return [SDAnswersDetectionModel shareInstance].resultDic.count == [SDAnswersDetectionModel shareInstance].dataArray.count;
    
}
- (NSString *)getAllAnswers
{
   __block NSString *allAnswer = @"";
    NSDictionary *resultDic = [SDAnswersDetectionModel shareInstance].resultDic;
    for (int r = 0; r < [SDAnswersDetectionModel shareInstance].dataArray.count; r++) {
        
        
        SDAnswerTestData *showData = [SDAnswersDetectionModel shareInstance].dataArray[r];
        SDAnswerTestResultData *data = resultDic[[NSString stringWithFormat:@"%d",r+1]];
        
        allAnswer = allAnswer.length == 0? [NSString stringWithFormat:@"%.f:%@",showData.id,data.option]:[NSString stringWithFormat:@"%@,%.f:%@",allAnswer,showData.id,data.option];
        
    }
    
    return allAnswer;
    
}
- (NSString *)getAnswerWithTag:(int)tag
{
    return tag == 1? @"A":tag == 2? @"B":tag == 3? @"C":tag == 4? @"D":tag == 5? @"E":tag == 6? @"F":tag == 7? @"G":tag == 8? @"H":@"I";
}
- (void)showResultWithDic:(NSDictionary *)dic
{
    SDAnswerTestResultData *data = [SDAnswerTestResultData modelObjectWithDictionary:dic];
    [[SDAnswersDetectionModel shareInstance].resultDic setObject:data forKey:[NSString stringWithFormat:@"%lu",(unsigned long)[SDAnswersDetectionModel shareInstance].answerTestType]];
    [self showView];
    [self.collectionView reloadData];
    
}
- (void)getTopTitleWithStr:(NSString *)str
{
    NSString *strLast = [str componentsSeparatedByString:@"$"].lastObject;
    NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:[str stringByReplacingOccurrencesOfString:@"$" withString:@""]];
    [att addAttribute:NSForegroundColorAttributeName value:rgba(255, 120, 155, 1) range:NSMakeRange(att.length - strLast.length, strLast.length)];
    [self.topLab setAttributedText:att];
    
}
- (void)getResultWithAnswer:(NSString *)answer
{
    
    SDAnswerTestData *data = [SDAnswersDetectionModel shareInstance].dataArray[[SDAnswersDetectionModel shareInstance].answerTestType - 1];
    
    [SDNetwork getQuestionResultWithID:data.id Answer:answer Finish:^(NSDictionary * _Nullable dic, NSError * _Nullable error) {
        
        if (!error)
        {
            
            [self showResultWithDic:dic[@"data"]];
            if ([self isCreateTestReport])[self createTestReport];
            
        }
        
    }];
    
}
- (IBAction)back:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
